#!/usr/bin/env bash
# Copyright (c) 2021-2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

#
# the install requires from yum.release.repo
# the build requires from yum.source.repo
#

__dnf_options=()

# dnf_set_global_option options
#   Set the global options of dnf
# Params:
#   options - like: "--repo yumrepo1 --repo yumrepo2"
dnf_set_global_option() {
    __dnf_options=("$@")
}

dnf_format_symbol() {
    sed -e 's/^(//' -e 's/ \+.*//'
}

# dnf_get_pkgname pkgs
#   Get the name of rpm packages
# Params:
#   pkgs - the rpm packages (removed .rpm)
dnf_get_pkgname() {
    local pkgs="$1"
    for p in $pkgs; do
        # local name=$(dnf info $p ${__dnf_options[@]} 2>/dev/null | grep -E "Name\s+:" | head -n1 | awk '{print $3}')
        echo "$p" | sed -r 's/-[^-]+-[^-]+$//g'
    done
}

# dnf_get_whatprovides symbol
#   Get the name of rpm that privides the symbol
# Params:
#   symbol - the provided symbol
dnf_get_whatprovides() {
    dnf repoquery --whatprovides "$1" ${__dnf_options[@]} -q 2>/dev/null | uniq
}

# dnf_get_whatrequires symbol
#   Get the name of rpm that installrequires the symbol
# Params:
#   symbol - the provided symbol
dnf_get_whatrequires() {
    dnf repoquery --whatrequires "$1" ${__dnf_options[@]} 2>/dev/null | uniq
}

# dnf_get_requires pkg
#   Get the requires symbol of pkg
# Params:
#   pkg - the name of rpm
dnf_get_requires() {
    dnf repoquery "$1" --requires ${__dnf_options[@]} 2>/dev/null
}

# dnf_get_provides pkg
#   Get the provides symbol of pkg
dnf_get_provides() {
    dnf repoquery "$1" --provides ${__dnf_options[@]} 2>/dev/null
}

# dnf_get_source pkg
#   Get the src name by rpm name
# Params:
#   pkg - the name of rpm (removed .release .rpm)
# Returns:
#   the name of src.rpm
dnf_get_source() {
    local info=$(dnf repoquery -q -i "$1" ${__dnf_options[@]} 2>/dev/null)
    local src=$(echo "$info" | grep -E "^Source\s+:" | grep -v "None" | head -n1)
    local name=""
    if [ -n "$src" ]; then
        src=$(echo "$src" | awk '{print $3}' | sed 's/\.rpm$//g')
        name=$(dnf_get_pkgname "$src")
    else
        name=$(echo "$info" | grep -E "^Name\s+:" | head -n1 | awk '{print $3}')
    fi
    echo "$name"
}

dnf_docheck() {
    check_command "dnf"
}
